<template>
    <div class="com-container">
        <!-- 柱状图 -->
        <div ref="chartDom" class="com-chart"></div>
        <TableDetail v-if="detailDialog" :detailDialog="detailDialog" :info="info" @closeDialog="closeDialog"></TableDetail>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import * as echarts from 'echarts';
import TableDetail from './table-detail.vue';

@Component({
    name: 'BarChart',
    components: {
        TableDetail,
    },
})
export default class BarChart extends Vue {
    @Prop() data;
    @Prop() chartName: string;
    @Prop({
        default: () => {
            return {};
        },
    })
    date: any;
    @Prop({ default: false }) isDetail: boolean;
    chartInstance: any = null;
    detailDialog: boolean = false;
    title: string = '监听表分布详情';

    // 静态触警分组
    emphasisStyle = {
        itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.3)',
        },
    };
    // 渲染颜色 todo
    colorArr: any = [
        '#d9001b',
        '#70b603',
        '#47bff4',
        '#a36200',
        '#c280ff',
        '#0000ff',
        '#8094ff',
        '#bfbf00',
        '#7b4d12',
        '#fac858',
        '#ec808d',
        '#6300bf',
        '#450eff',
        '#6e1b4e',
        '#b3d1f3',
    ];
    info: any = {};

    @Watch('data', { immediate: true, deep: true })
    onWatchData(newData) {
        if (newData) {
            let that = this;
            this.$nextTick(() => {
                that.updateChart(newData);
            });
        }
    }

    @Watch('date', { immediate: true, deep: true })
    handleInfo() {
        this.info.startDate = this.date.startDate;
        this.info.endDate = this.date.endDate;
    }
    // 柱状图点击
    handleBarClick(name: string, dataIndex: number) {
        if (this.isDetail) {
            return;
        }
        if (this.chartName == 'menu') {
            this.info.resourceCode = this.data.xData[dataIndex].split(':')[0];
        } else {
            this.info.operateNo = this.data.xData[dataIndex].split(':')[0];
        }
        this.info.title = this.data.title;
        this.info.name = name;
        this.detailDialog = true;
    }

    mounted() {
        const xTitle = this.data.title;
        this.$set(window, xTitle, this.handleBarClick);
        this.initChart();
    }

    initChart() {
        this.chartInstance = echarts.init(this.$refs.chartDom);
        const xTitle = this.data.title;
        const initOption = {
            color: ['#107fff'],
            legend: {
                show: false,
            },
            tooltip: {
                trigger: 'axis',
                triggerOn: 'mousemove',
                enterable: true, // 鼠标是否可进入提示框浮层中
                confine: true, // 是否将 tooltip 框限制在图表的区域内
                extraCssText: 'z-index: 99;', // 额外附加到浮层的 css 样式
                position: function(p) {
                    // 其中p为当前鼠标的位置
                    return [p[0] + 15, p[1] - 15];
                },
                backgroundColor: 'rgba(255,255,255,0.8)',
                borderColor: 'rgba(0,0,0,0.1)',
                textStyle: {
                    color: 'rgba(0, 0, 0, 0.65)',
                },

                formatter: params => {
                    let values: any[] = [];
                    let colors: any[] = [];
                    const name = this.chartName == 'menu' ? params[0].name.split(':')[1] : '访问次数';
                    const marker = params[0].marker;
                    params.forEach(ele => {
                        values.push(ele.value);
                        colors.push(ele.color);
                    });
                    if (this.isDetail) {
                        return `${marker}${name}:<span style="color:${colors[0]};margin:0 3px;font-size:8px;cursor:pointer;" onclick="${xTitle}('${params[0].name}','${params[0].dataIndex}')">${values[0]}次</span>`;
                    } else {
                        return `${marker}${name}:<span style="border-bottom:1px solid ${colors[0]};color:${colors[0]};margin:0 3px;font-size:8px;cursor:pointer;" onclick="${xTitle}('${params[0].name}','${params[0].dataIndex}')">${values[0]}次</span>`;
                    }
                },
                axisPointer: {
                    type: 'none',
                },
            },
            xAxis: {
                data: this.data.xData,
                axisLine: {
                    lineStyle: {
                        color: '#8ab09c',
                        width: 1,
                    },
                },
                triggerEvent: true,
                // 设置文本过长超出隐藏...表示
                axisLabel: {
                    interval: 0,
                    color: '#333333',
                    formatter: params => {
                        if (this.chartName == 'menu') {
                            params = params.split('-')[1];
                        } else if (this.chartName == 'user') {
                            params = params.split(':')[1];
                        }
                        let val = '';
                        if (params && params.length > 5) {
                            val = params.substr(0, 5) + '...';
                            return val;
                        } else {
                            return params;
                        }
                    },
                },
                axisTick: {
                    show: true,
                    inside: false,
                    alignWithLabel: true,
                },
            },
            yAxis: {
                splitNumber: 3,
                // offset: -11,
                // splitLine: {
                //     show: true,
                //     lineStyle: {
                //         color: '#cccccc',
                //         width: 1,
                //     },
                // },
                axisLabel: {
                    color: '#8c8c8c',
                    formatter: '{value}次',
                    showMinLabel: false,
                },
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#cccccc',
                        width: 1,
                    },
                },
            },
            dataZoom: [
                {
                    type: 'inside',
                    height: 12,
                    bottom: 0,
                    startValue: 0,
                    endValue: 10,
                    showDetail: false,
                    minValueSpan: 1,
                    maxValueSpan: 15,
                },
                {
                    height: 12,
                    bottom: 0,
                    showDetail: false,
                    startValue: 0,
                    endValue: 10,
                },
            ],
            grid: {
                left: '2%',
                right: '2%',
                top: '25%',
                bottom: '3%',
                height: '66%', // 高度
                containLabel: true,
            },
            series: [
                {
                    name: 'Direct',
                    type: 'bar',
                    barWidth: '40%',
                    data: (() => {
                        if (this.chartName == 'menu') {
                            return this.data.data.map((item, index) => {
                                return {
                                    value: item,
                                    itemStyle: {
                                        color: this.colorArr[index % 15],
                                    },
                                };
                            });
                        } else {
                            return this.data.data;
                        }
                    })(),
                },
            ],
        };
        this.chartInstance.setOption(initOption);
        this.extension(this.chartInstance);
    }

    // 鼠标悬浮显示全部内容
    extension(chart) {
        // 注意这里，是以X轴显示内容过长为例，如果是x轴的话，需要把params.componentType == 'xAxis'改为yAxis
        // 判断是否创建过div框,如果创建过就不再创建了
        // 该div用来盛放文本显示内容的，方便对其悬浮位置进行处理
        let elementDiv: any = document.getElementById('extension');
        if (!elementDiv) {
            let div = document.createElement('div');
            div.setAttribute('id', 'extension');
            div.style.display = 'block';
            document.querySelector('html').appendChild(div);
        }
        const that = this;
        chart.on('mouseover', function(params) {
            if (params.componentType == 'xAxis') {
                let elementDiv = document.querySelector('#extension') as HTMLElement;
                // 设置悬浮文本的位置以及样式
                let elementStyle =
                    'position: absolute;z-index: 99999;color: #fff;font-size: 12px;padding: 5px;display: inline;border-radius: 4px;background-color: #303133;box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 8px';
                elementDiv.style.cssText = elementStyle;
                if (that.chartName == 'menu') {
                    elementDiv.innerHTML = params.value.split('-')[1];
                } else {
                    elementDiv.innerHTML = params.value.split(':')[1];
                }
                const text = elementDiv.innerHTML;
                if (text && text.length <= 5) {
                    elementDiv.style.cssText = 'display:none';
                }
                document.querySelector('html').onmousemove = function(event) {
                    let elementDiv = document.querySelector('#extension') as HTMLElement;
                    let xx = event.pageX - 10;
                    let yy = event.pageY + 15;
                    elementDiv.style.top = yy + 'px';
                    elementDiv.style.left = xx + 'px';
                };
            }
        });
        chart.on('mouseout', function(params) {
            if (params.componentType == 'xAxis') {
                let elementDiv = document.querySelector('#extension') as HTMLElement;
                elementDiv.style.cssText = 'display:none';
            }
        });
    }

    closeDialog() {
        this.detailDialog = false;
    }
    updateChart(e) {
        const dataOption = {
            xAxis: { data: e.xData },
            series: {
                data: (() => {
                    if (this.chartName == 'menu') {
                        return this.data.data.map((item, index) => {
                            return {
                                value: item,
                                itemStyle: {
                                    color: this.colorArr[index % 15],
                                },
                            };
                        });
                    } else {
                        // console.log(this.data.data);
                        return this.data.data;
                    }
                })(),
            },
        };
        this.chartInstance.setOption(dataOption);
        this.extension(this.chartInstance); // 这个方法是用来处理鼠标悬浮显示全部内容的
        // 点击事件
        console.log(this.chartInstance);
        this.chartInstance.on('click', param => {
            this.handleBarClick(param.name, param.dataIndex);
        });
    }
}
</script>

<style scoped>
.com-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.com-chart {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
